#include "VehicleManager.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>

VehicleManager::VehicleManager() {}

void VehicleManager::initializeVehicles() {
    vehicles.clear();
    
    // 初始化10台智能小车
    for (int i = 1; i <= 10; i++) {
        std::stringstream ss;
        ss << "cqusn2023000" << std::setfill('0') << std::setw(2) << i;
        std::string vehicleId = ss.str();
        
        Vehicle vehicle(vehicleId);
        
        // 设置底盘信息
        Chassis chassis("dp2023000" + std::to_string(i), "SCOUT MINI", 451, 490, 115, 0,
                        "四轮四驱", 10, "公路轮、麦克纳姆轮", 175);
        vehicle.setChassis(chassis);
        
        // 设置AGX套件信息
        AGXKit agxKit("AGX Xavier", 32, 512, 64, 32, 32);
        vehicle.setAgxKit(agxKit);
        
        // 设置双目摄像头信息
        StereoCamera stereoCamera("RealSense D435i", "D430", "1920*1080", 30, "87*58", 90);
        vehicle.setStereoCamera(stereoCamera);
        
        // 设置多线激光雷达信息
        Lidar lidar("RS-Helios-16p", 16, 100, 8);
        vehicle.setLidar(lidar);
        
        // 设置9轴陀螺仪信息
        Gyroscope gyroscope("CH110", "NXP");
        vehicle.setGyroscope(gyroscope);
        
        // 设置液晶显示屏信息
        Display display(11.6, "super");
        vehicle.setDisplay(display);
        
        // 设置电池模块信息
        Battery battery("24V/15Ah", 24, 2);
        vehicle.setBattery(battery);
        
        vehicles.push_back(vehicle);
    }
}

void VehicleManager::assignVehiclesToStudents() {
    // 将小车分配给学生
    for (size_t i = 0; i < vehicles.size(); i++) {
        std::stringstream ss;
        ss << "2023000" << std::setfill('0') << std::setw(2) << (i + 1);
        std::string studentId = ss.str();
        std::string studentName = "学生" + std::to_string(i + 1);
        
        Student student(studentId, studentName);
        vehicles[i].setStudent(student);
    }
}

void VehicleManager::saveToFile(const std::string& filename) {
    std::ofstream file(filename);
    if (!file.is_open()) {
        std::cerr << "无法打开文件: " << filename << std::endl;
        return;
    }
    
    for (const auto& vehicle : vehicles) {
        // 写入小车信息
        file << "Vehicle:" << vehicle.getId() << std::endl;
        
        // 写入底盘信息
        Chassis chassis = vehicle.getChassis();
        file << "Chassis:" << chassis.getId() << "," << chassis.getModel() << "," 
             << chassis.getWheelbase() << "," << chassis.getTrack() << "," 
             << chassis.getMinGroundClearance() << "," << chassis.getMinTurningRadius() << ","
             << chassis.getDriveMode() << "," << chassis.getMaxRange() << ","
             << chassis.getTireModel() << "," << chassis.getTireSize() << std::endl;
        
        // 写入AGX套件信息
        AGXKit agxKit = vehicle.getAgxKit();
        file << "AGXKit:" << agxKit.getModel() << "," << agxKit.getAi() << ","
             << agxKit.getCudaCores() << "," << agxKit.getTensorCores() << ","
             << agxKit.getMemory() << "," << agxKit.getStorage() << std::endl;
        
        // 写入双目摄像头信息
        StereoCamera stereoCamera = vehicle.getStereoCamera();
        file << "StereoCamera:" << stereoCamera.getModel() << "," << stereoCamera.getCamera() << ","
             << stereoCamera.getRgbResolution() << "," << stereoCamera.getRgbFrameRate() << ","
             << stereoCamera.getFov() << "," << stereoCamera.getDepthFrameRate() << std::endl;
        
        // 写入多线激光雷达信息
        Lidar lidar = vehicle.getLidar();
        file << "Lidar:" << lidar.getModel() << "," << lidar.getChannels() << ","
             << lidar.getRange() << "," << lidar.getPower() << std::endl;
        
        // 写入9轴陀螺仪信息
        Gyroscope gyroscope = vehicle.getGyroscope();
        file << "Gyroscope:" << gyroscope.getModel() << "," << gyroscope.getManufacturer() << std::endl;
        
        // 写入液晶显示屏信息
        Display display = vehicle.getDisplay();
        file << "Display:" << display.getSize() << "," << display.getModel() << std::endl;
        
        // 写入电池模块信息
        Battery battery = vehicle.getBattery();
        file << "Battery:" << battery.getParameter() << "," << battery.getOutputVoltage() << ","
             << battery.getChargeTime() << std::endl;
        
        // 写入学生信息
        Student student = vehicle.getStudent();
        file << "Student:" << student.getStudentId() << "," << student.getName() << std::endl;
        file << "---" << std::endl;
    }
    
    file.close();
}

void VehicleManager::loadFromFile(const std::string& filename) {
    std::ifstream file(filename);
    if (!file.is_open()) {
        std::cerr << "无法打开文件: " << filename << std::endl;
        return;
    }
    
    vehicles.clear();
    std::string line;
    Vehicle currentVehicle;
    
    while (std::getline(file, line)) {
        if (line.empty() || line == "---") {
            if (!currentVehicle.getId().empty()) {
                vehicles.push_back(currentVehicle);
                currentVehicle = Vehicle();
            }
            continue;
        }
        
        size_t colonPos = line.find(':');
        if (colonPos == std::string::npos) continue;
        
        std::string type = line.substr(0, colonPos);
        std::string data = line.substr(colonPos + 1);
        
        if (type == "Vehicle") {
            currentVehicle = Vehicle(data);
        } else if (type == "Chassis") {
            std::stringstream ss(data);
            std::string id, model, tireModel;
            double wheelbase, track, minGroundClearance, minTurningRadius, maxRange, tireSize;
            std::string driveMode;
            char comma;
            
            std::getline(ss, id, ',');
            std::getline(ss, model, ',');
            ss >> wheelbase >> comma >> track >> comma >> minGroundClearance >> comma 
               >> minTurningRadius >> comma >> driveMode >> comma >> maxRange >> comma;
            std::getline(ss, tireModel, ',');
            ss >> tireSize;
            
            Chassis chassis(id, model, wheelbase, track, minGroundClearance, 
                            minTurningRadius, driveMode, maxRange, tireModel, tireSize);
            currentVehicle.setChassis(chassis);
        } else if (type == "AGXKit") {
            std::stringstream ss(data);
            std::string model;
            double ai;
            int cudaCores, tensorCores, memory, storage;
            char comma;
            
            std::getline(ss, model, ',');
            ss >> ai >> comma >> cudaCores >> comma >> tensorCores >> comma 
               >> memory >> comma >> storage;
            
            AGXKit agxKit(model, ai, cudaCores, tensorCores, memory, storage);
            currentVehicle.setAgxKit(agxKit);
        } else if (type == "StereoCamera") {
            std::stringstream ss(data);
            std::string model, camera, rgbResolution, fov;
            int rgbFrameRate, depthFrameRate;
            char comma;
            
            std::getline(ss, model, ',');
            std::getline(ss, camera, ',');
            std::getline(ss, rgbResolution, ',');
            ss >> rgbFrameRate >> comma;
            std::getline(ss, fov, ',');
            ss >> depthFrameRate;
            
            StereoCamera stereoCamera(model, camera, rgbResolution, rgbFrameRate, fov, depthFrameRate);
            currentVehicle.setStereoCamera(stereoCamera);
        } else if (type == "Lidar") {
            std::stringstream ss(data);
            std::string model;
            int channels;
            double range, power;
            char comma;
            
            std::getline(ss, model, ',');
            ss >> channels >> comma >> range >> comma >> power;
            
            Lidar lidar(model, channels, range, power);
            currentVehicle.setLidar(lidar);
        } else if (type == "Gyroscope") {
            std::stringstream ss(data);
            std::string model, manufacturer;
            
            std::getline(ss, model, ',');
            std::getline(ss, manufacturer);
            
            Gyroscope gyroscope(model, manufacturer);
            currentVehicle.setGyroscope(gyroscope);
        } else if (type == "Display") {
            std::stringstream ss(data);
            double size;
            std::string model;
            char comma;
            
            ss >> size >> comma;
            std::getline(ss, model);
            
            Display display(size, model);
            currentVehicle.setDisplay(display);
        } else if (type == "Battery") {
            std::stringstream ss(data);
            std::string parameter;
            double outputVoltage, chargeTime;
            char comma;
            
            std::getline(ss, parameter, ',');
            ss >> outputVoltage >> comma >> chargeTime;
            
            Battery battery(parameter, outputVoltage, chargeTime);
            currentVehicle.setBattery(battery);
        } else if (type == "Student") {
            std::stringstream ss(data);
            std::string studentId, name;
            
            std::getline(ss, studentId, ',');
            std::getline(ss, name);
            
            Student student(studentId, name);
            currentVehicle.setStudent(student);
        }
    }
    
    // 添加最后一辆小车（如果没有以---结尾）
    if (!currentVehicle.getId().empty()) {
        vehicles.push_back(currentVehicle);
    }
    
    file.close();
}

void VehicleManager::displayVehicle(int index) const {
    if (index >= 0 && index < (int)vehicles.size()) {
        vehicles[index].show();
    } else {
        std::cout << "无效的小车索引。" << std::endl;
    }
}

size_t VehicleManager::getVehicleCount() const {
    return vehicles.size();
}